package com.kehao.accountbook.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kehao.accountbook.AccountApplication;
import com.kehao.accountbook.AddExpendActivity;
import com.kehao.accountbook.MainActivity;
import com.kehao.accountbook.ModifyExpendActivity;
import com.kehao.accountbook.R;
import com.kehao.accountbook.adapter.ExpenditureAdapter;
import com.kehao.accountbook.network.Network;
import com.kehao.accountbook.pojo.Expenditure;
import com.kehao.accountbook.pojo.SimpleDate;
import com.kehao.accountbook.pojo.SimpleTime;

import org.litepal.LitePal;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

public class MainFragment extends Fragment {
    private static final int REQUEST_CODE_ADD_EXPEND = 1;
    public static final int REQUEST_CODE_MODIFY_EXPEND = 2;
    private static final int RESULT_CODE_DELETE = 10;

    RecyclerView recyclerView;
    List<Expenditure> list;
    TextView tv_pay;
    TextView tv_get;
    TextView tv_pure;
    ImageView imageView;
    Button button;
    double pay,get;
    boolean flag = true;
    public TextView tv_mode;
    public Handler handler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        recyclerView = view.findViewById(R.id.rv_expend);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        SimpleDate date = new SimpleDate();
        list = LitePal.where("month = ? and year = ? and username = ? and status != ?",
                Integer.toString(date.getMonth()),Integer.toString(date.getYear()),
                getAccountApplication().getUsername(),Integer.toString(Expenditure.STATUS_REMOVE))
                .order("day , hour , min , second")
                .find(Expenditure.class);
        ExpenditureAdapter adapter = new ExpenditureAdapter(list);
        adapter.listener = new ExpenditureAdapter.ItemClickListener(){
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ModifyExpendActivity.class);
                intent.putExtra("item",list.get(position));
                startActivityForResult(intent,REQUEST_CODE_MODIFY_EXPEND);
            }
        };
        recyclerView.setAdapter(adapter);
        tv_pay = view.findViewById(R.id.tv_money_pay);
        tv_get = view.findViewById(R.id.tv_money_get);
        tv_pure = view.findViewById(R.id.tv_purepay);
        tv_mode = view.findViewById(R.id.tv_offline_mode);
        imageView = view.findViewById(R.id.img_hide);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag){//hide
                    imageView.setImageResource(R.drawable.show_money);
                    tv_get.setText("本月收入： ***");
                    tv_pay.setText("******");
                    tv_pure.setText("净支出： ***");
                }else {//show
                    imageView.setImageResource(R.drawable.hide_money);
                    tv_pay.setText("￥"+(-pay));
                    tv_get.setText("本月收入： "+(get!=0?get:"暂无收入"));
                    tv_pure.setText("净支出： "+(-(get+pay)));
                }
                flag = !flag;
            }
        });
        button = view.findViewById(R.id.btn_add);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddExpendActivity.class);
                startActivityForResult(intent,REQUEST_CODE_ADD_EXPEND);
            }
        });
        updateUI();
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case 1:
                        if(getAccountApplication().NetworkMode()){
                            tv_mode.setVisibility(View.INVISIBLE);
                        }else {
                            tv_mode.setVisibility(View.VISIBLE);
                        }
                        break;
                    case 2:
                        recyclerView.getAdapter().notifyDataSetChanged();
                        break;

                }
            }
        };
        Network.handler = handler;
        SimpleDate simpleDate = new SimpleDate();
        getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
        recyclerView.getAdapter().notifyDataSetChanged();
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SimpleDate simpleDate = new SimpleDate();
        switch (requestCode){
            case REQUEST_CODE_ADD_EXPEND:
                if(resultCode == Activity.RESULT_OK){
                    Expenditure expenditure = (Expenditure) data.getSerializableExtra("item");
                    expenditure.setStatus(Expenditure.STATUS_ADD);
                    expenditure.save();
                    list.add(expenditure);
                    recyclerView.getAdapter().notifyItemChanged(list.size()-1);
                    updateUI();
                    getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
                }
                break;
            case REQUEST_CODE_MODIFY_EXPEND:
                if(resultCode == Activity.RESULT_OK){
                    Expenditure expenditure = (Expenditure) data.getSerializableExtra("item");
                    resetList();//重新加载列表 否则这次本地先提交的数据是原先的list进行更新然后会产生上次网络端更新的anchor被覆盖掉了
                    for(int i =0;i<list.size();i++){
                        Expenditure e = list.get(i);
                        if(e.getDay()==expenditure.getDay() &&e.getHour()==expenditure.getHour()
                                &&e.getMin()==expenditure.getMin()&&e.getSecond()==expenditure.getSecond()){
                            e.setType(expenditure.getType());
                            e.setComment(expenditure.getComment());
                            e.setMoney(expenditure.getMoney());
                            e.setStatus(Expenditure.STATUS_LOCAL_CHANGE);
                            e.save();
                            updateUI();
                            recyclerView.getAdapter().notifyDataSetChanged();
                            break;
                        }
                    }
                    updateUI();
                    getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
                    Log.e("MainFragment", "onActivityResult:modify ok "+expenditure.toString() );
                }else if(resultCode==RESULT_CODE_DELETE){
                    Expenditure expenditure = (Expenditure) data.getSerializableExtra("item");
                    resetList();
                    for(int i =0;i<list.size();i++){
                        Expenditure e = list.get(i);
                        if(e.getDay()==expenditure.getDay() &&e.getHour()==expenditure.getHour()
                                &&e.getMin()==expenditure.getMin()&&e.getSecond()==expenditure.getSecond()){
                            /*e.delete();是真删除，假删除是在anchor上做标记
                             * */
                            e.setStatus(Expenditure.STATUS_REMOVE);
                            e.save();
                            list.remove(i);
                            updateUI();
                            recyclerView.getAdapter().notifyDataSetChanged();
                            break;
                        }
                    }
                    getAccountApplication().syncData(simpleDate.getYear(),simpleDate.getMonth());
                    Log.e("MainFragment", "onActivityResult:remove ok "+expenditure.toString() );
                }
                else {
                    Log.e("MainFragment", "onActivityResult: cancel" );
                }
                break;
        }
    }

    private void resetList() {
        list.clear();
        SimpleDate date = new SimpleDate();
        list = ((ExpenditureAdapter) recyclerView.getAdapter()).expenditureList =
                LitePal.where("month = ? and year = ? and username = ? and status != ?",
                        Integer.toString(date.getMonth()), Integer.toString(date.getYear()),
                        getAccountApplication().getUsername(), Integer.toString(Expenditure.STATUS_REMOVE))
                        .order("day , hour , min , second")
                        .find(Expenditure.class);
    }


    private void updateUI() {
        pay = 0;
        get = 0;
        for (Expenditure i :list){
            double money = i .getMoney();
            if(money>0){
                get+=money;
            }else if(money<0){
                pay+=money;
            }
        }
        if(pay!=0){
            tv_pay.setText("￥"+(-pay));
        }else {
            tv_pay.setText("暂无支出");
        }
        if(get!=0){
            tv_get.setText("本月收入： "+get);
        }else {
            tv_get.setText("本月收入： 暂无收入");
        }
        tv_pure.setText("净支出： "+(-(get+pay)));

    }

    public void refreshView(){
        SimpleDate todayDate = new SimpleDate();
        ((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList.clear();
        list = ((ExpenditureAdapter)recyclerView.getAdapter()).expenditureList =
                LitePal.where("month = ?",Integer.toString(todayDate.getMonth()))
                        .where("year = ?",Integer.toString(todayDate.getYear()))
                        .where("username = ?", getAccountApplication().getUsername())
                        .order("day , hour , min , second")
                        .find(Expenditure.class);
        recyclerView.getAdapter().notifyDataSetChanged();

        updateUI();
    }

    private AccountApplication getAccountApplication(){
        return (AccountApplication)getActivity().getApplication();
    }


}
